<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${dataId ? '编辑' : '新增'}-区域开台记录`"
		width="900px"
		:confirm-btn-loading="saveBtnLoading"
		fullscreen
		:permission-prefix="permissionPrefix"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<div ref="box1">
			<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="90px" :show-message="false">
				<el-row class="flex-start-center-wrap">
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="区域" prop="workshopId">
							<span v-if="ruleForm.id" class="read-only-2">{{ ruleForm.workshopName }}</span>
							<jk-select v-else v-model="ruleForm.workshopId" :option-list="workshopList" size="medium" class="width-100-percent" placeholder="区域" @change="onWorkshopChange"></jk-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="区域">
							<span v-if="ruleForm.id" class="read-only-2">{{ ruleForm.workshopAreaName }}</span>
							<jk-select v-else v-model="ruleForm.workshopAreaId" :clearable="true" size="medium" :disabled="!ruleForm.workshopId" :option-list="workshopAreaList" class="width-100-percent" placeholder="区域" @change="onWorkshopAreaChange"></jk-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="日期" prop="belongDate">
							<span v-if="ruleForm.id" class="read-only-2">{{ ruleForm.belongDate }}</span>
							<jk-date-picker v-else v-model="ruleForm.belongDate" type="date" size="medium" placeholder="日期" @change="onDateChange" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="班次" prop="scheduleShiftId">
							<span v-if="ruleForm.id" class="read-only-2">{{ ruleForm.scheduleShiftName }}</span>
							<el-select v-else v-model="ruleForm.scheduleShiftId" :disabled="!!ruleForm.id || !ruleForm.belongDate" clearable placeholder="班次" size="medium" class="width-100-percent" @change="onScheduleShiftChange">
								<el-option
									v-for="item in scheduleShiftList"
									:key="item.id"
									:label="`${item.shiftName} (${item.beginTime} ~ ${item.endTime})`"
									:value="item.id"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="班组" prop="scheduleGroupId">
							<span v-if="ruleForm.id" class="read-only-2">{{ ruleForm.scheduleGroupName }}</span>
							<jk-select v-else v-model="ruleForm.scheduleGroupId" :disabled="!ruleForm.scheduleShiftId" :option-list="groupList" size="medium" label-key-name="groupName" class="width-100-percent" placeholder="班组" @change="onGroupChange"></jk-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="统计员" prop="empId">
							<remote-search-emp-input
								size="medium"
								placeholder="统计员"
								only-key="empId"
								query-name="empName"
								:form-data="ruleForm"
								@on-select="onSelectEmpChange"
							></remote-search-emp-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item class="margin-bottom-10" label="备注">
							<el-input v-model="ruleForm.remark" type="textarea" :rows="1"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</div>
		<el-row :gutter="10">
			<el-col :span="15">
				<div class="option-item-title">开台品种({{ ruleForm.productList.length || 0 }}个)</div>
				<jk-table :loading="showLoading" :footer-method="footerMethod" :show-footer="true" :height="dialogTableHeight + 42" border :data="ruleForm.productList">
					<vxe-column title="操作" align="center" field="operation" :width="62">
						<template slot-scope="scope">
							<el-button icon="el-icon-delete" size="mini" @click="onDeleteRowBtn(scope)"></el-button>
						</template>
					</vxe-column>
					<!--<vxe-column title="序号" align="center" type="seq" :width="50" />-->
					<vxe-column title="规格" align="left" field="productModels" :min-width="110" />
					<vxe-column title="批号" align="left" field="batchCode" :min-width="100"></vxe-column>
					<vxe-column title="上机数" align="right" field="upQty" :width="70" />
					<vxe-column title="关台数" align="right" field="closeQty" :width="90">
						<template slot-scope="scope">
							<jk-number-input v-model="scope.row.closeQty" size="mini"></jk-number-input>
						</template>
					</vxe-column>
					<vxe-column title="实际开台" align="right" field="openQty" :width="100">
						<template slot-scope="scope">
							<jk-number-input v-model="scope.row.openQty" size="mini"></jk-number-input>
						</template>
					</vxe-column>
				</jk-table>
			</el-col>
			<!--<el-col :span="9">
				<div class="option-item-title">络筒机台({{ ruleForm.matchProductList.length || 0 }}组)</div>
				<jk-table :loading="showLoading" :height="dialogTableHeight + 42" :span-method="mergeColMethod" border :data="ruleForm.matchProductList">
					<vxe-column title="机台" align="left" field="machineName" :width="70"></vxe-column>
					<vxe-column title="锭组" align="left" field="number" :width="60"></vxe-column>
					<vxe-column title="规格" align="left" field="productModels" :min-width="110" />
					<vxe-column title="批号" align="left" field="batchCode" :min-width="100"></vxe-column>
					<vxe-column title="芋管" align="left" field="yuGuan" :min-width="100"></vxe-column>
					<vxe-column title="纸管" align="left" field="zhiGuan" :min-width="100"></vxe-column>
				</jk-table>
			</el-col>-->
			<el-col :span="9">
				<div class="option-item-title">人员考勤({{ ruleForm.empList.length || 0 }}人)</div>
				<jk-table :loading="showLoading" :footer-method="footerMethod" :show-footer="true" :height="dialogTableHeight + 42" border :data="ruleForm.empList">
					<vxe-column title="岗位" align="left" field="postName" :min-width="90" />
					<vxe-column title="到岗数" align="right" field="totalQty" :min-width="80">
						<template slot-scope="scope">
							<jk-number-input v-model="scope.row.totalQty" size="mini"></jk-number-input>
						</template>
					</vxe-column>
					<vxe-column title="请假数" align="right" field="zhiGuan" :min-width="80">
						<template slot-scope="scope">
							<jk-input v-model="scope.row.leaveQty" size="mini"></jk-input>
						</template>
					</vxe-column>
				</jk-table>
			</el-col>
		</el-row>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import {
        spinReportProductOpenRecordCreate,
        spinReportProductOpenRecordUpdate,
        spinReportProductOpenRecordGet, reportProductionOrderProductOpenRecord
    } from '../../../api/production/workshopAreaOpenRecord';
    import checkboxMachineDialog from '../../schedule/empMachine/components/checkbox-machine-dialog';
    import remoteSearchEmpInput from '../../production/order/components/remote-search-emp-input';
    import remoteSearchProductInput from '../../production/order/components/remote-search-product-input';
    import remoteSearchBatchCodeInput
        from '../../production/qhPrd/productConfigCotton/components/remote-search-batch-code-input';
    import { formatDate, tipsBar } from '../../../utils/jk/jk-tool';
    import { workforcemanagementScheduleList } from '../../../api/schedule/scheduling';
    import { spinWorkshopAreaPage } from '../../../api/basicData/workshopArea';
    import XEUtils from 'xe-utils';
    import { systemPostPage } from '../../../api/system/post';
    export default {
        name: 'CsUseMaterialStatistics',
        components: {
            remoteSearchBatchCodeInput,
            remoteSearchProductInput,
            checkboxMachineDialog,
            remoteSearchEmpInput
        },
        props: {
            // 页面权限的前缀
            permissionPrefix: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            defaultTypeCode: {
                type: String,
                default: ''
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        mixins: [calHeight],
        data() {
            return {
                allPost: [],
                postList: [],
                activeTab: '0',
                groupList: [],
                workshopList: [],
                showDialog: false,
                showLoading: true,
                saveBtnLoading: false,
                workshopAreaList: [],
                ruleForm: {
                    id: null,
                    workshopAreaId: null,
                    workshopAreaName: null,
                    scheduleGroupId: null,
                    belongDate: '',
                    empId: null,
                    empName: '',
                    remark: '',
                    workshopId: null,
                    processList: [],
                    productList: [],
                    empList: [],
                    matchProductList: []
                },
                rules: {
                    belongDate: [{ required: true, trigger: 'change' }],
                    scheduleGroupId: [{ required: true, trigger: 'change' }],
                    empId: [{ required: true, trigger: 'change' }],
                    workshopAreaId: [{ required: true, trigger: 'change' }],
                    scheduleShiftId: [{ required: true, trigger: 'change' }],
                    workshopId: [{ required: true, trigger: 'change' }]
                },
                scheduleShiftList: []
            };
        },
        methods: {
            onDeleteRowBtn(scope) {
                this.$delete(this.ruleForm.productList, scope.rowIndex, 1);
            },
            footerMethod({ columns, data }) {
                const keys = ['upQty', 'closeQty', 'openQty', 'totalQty', 'zhiGuan'];
                return [
                    columns.map((column, columnIndex) => {
                        if (columnIndex === 0) {
                            return '合计';
                        }
                        if (keys.includes(column.field)) {
                            return XEUtils.sum(data, column.field);
                        }
                        return null;
                    })
                ];
            },
            mergeColMethod({ row, _rowIndex, column, visibleData }) {
                const fields = ['machineName']; // 根据字段判断数据相同的合并
                const cellValue = row[column.property];
                if (cellValue && fields.includes(column.property)) {
                    const prevRow = visibleData[_rowIndex - 1];
                    let nextRow = visibleData[_rowIndex + 1];
                    if (prevRow && prevRow[column.property] === cellValue) {
                        return { rowspan: 0, colspan: 0 };
                    } else {
                        let countRowspan = 1;
                        while (nextRow && nextRow[column.property] === cellValue) {
                            nextRow = visibleData[++countRowspan + _rowIndex];
                        }
                        if (countRowspan > 1) {
                            return { rowspan: countRowspan, colspan: 1 };
                        }
                    }
                }
            },
            onWorkshopAreaChange() {
                this.getStatisticData();
            },
            onGroupChange(e) {
                this.$set(this.ruleForm, 'empList', []);
                this.$set(this.ruleForm, 'productList', []);
                this.$set(this.ruleForm, 'matchProductList', []);
                if (e) {
                    const scheduleGroupItem = this.groupList.find(x => x.id === e);
                    this.$set(this.ruleForm, 'scheduleGroupId', scheduleGroupItem.id);
                    this.$set(this.ruleForm, 'scheduleGroupCode', scheduleGroupItem.groupCode);
                    this.$set(this.ruleForm, 'scheduleGroupName', scheduleGroupItem.groupName);
                }
                this.getStatisticData();
            },
            getStatisticData() {
                if (!this.ruleForm.scheduleShiftId || !this.ruleForm.scheduleGroupId) return false;
                this.showLoading = true;
                reportProductionOrderProductOpenRecord({
                    workshopId: this.ruleForm.workshopId,
                    workshopAreaId: this.ruleForm.workshopAreaId,
                    scheduleShiftId: this.ruleForm.scheduleShiftId,
                    scheduleGroupId: this.ruleForm.scheduleGroupId
                }).then(res => {
                    this.showLoading = false;
                    if (res.data.status === 200) {
                        this.$set(this.ruleForm, 'productList', res.data.res.productList ? res.data.res.productList.map(x => {
                            return x;
                        }) : []);
                        this.$set(this.ruleForm, 'matchProductList', res.data.res.matchProductList ? res.data.res.matchProductList.map(x => {
                            return x;
                        }) : []);
                        this.setEmpList(res.data.res.empList || []);
                    }
                });
            },
            setEmpList(data = []) {
                let cpPostList = JSON.parse(JSON.stringify(this.postList));
                const filterArr = data.filter(x => !cpPostList.map(k => k.postId).includes(x.postId));
                filterArr.forEach(x => {
                    if (this.allPost.some(k => k.postId === x.postId)) {
                        x.sortNum = this.allPost.find(k => k.postId === x.postId).sortNum;
                    }
                });
                cpPostList = [...cpPostList, ...filterArr];
                cpPostList = cpPostList.sort((a, b) => {
                    return a.sortNum - b.sortNum;
                });
                cpPostList.forEach(x => {
                    data.forEach(k => {
                        if (x.postId === k.postId) {
                            x.totalQty = k.totalQty;
                            x.leaveQty = k.leaveQty;
                        }
                    });
                });
                this.$set(this.ruleForm, 'empList', cpPostList);
            },
            onWorkshopChange() {
                this.$set(this.ruleForm, 'scheduleGroupId', null);
                this.$set(this.ruleForm, 'workshopAreaId', null);
                this.$set(this.ruleForm, 'scheduleId', null);
                this.$set(this.ruleForm, 'scheduleShiftId', null);
                this.$set(this.ruleForm, 'shiftId', null);
                this.$set(this.ruleForm, 'shiftName', null);
                this.scheduleShiftList = [];
                this.$set(this.ruleForm, 'empList', []);
                this.$set(this.ruleForm, 'productList', []);
                this.$set(this.ruleForm, 'matchProductList', []);
                this.getDateScheduleShiftOptionRequest();
            },
            onScheduleShiftChange(e) {
                let item = {};
                if (e) {
                    item = this.scheduleShiftList.find(x => x.id === e);
                } else {
                    item = {
                        id: null,
                        shiftId: null,
                        shiftName: null,
                        scheduleId: null
                    };
                }
                this.groupList = item.scheduleGroupList;
                this.$set(this.ruleForm, 'empList', []);
                this.$set(this.ruleForm, 'productList', []);
                this.$set(this.ruleForm, 'matchProductList', []);
                this.$set(this.ruleForm, 'scheduleGroupId', null);
                this.$set(this.ruleForm, 'scheduleId', item.scheduleId);
                this.$set(this.ruleForm, 'scheduleShiftId', item.id);
                this.$set(this.ruleForm, 'scheduleShiftCode', item.shiftCode);
                this.$set(this.ruleForm, 'scheduleShiftName', item.shiftName);
            },
            onDateChange() {
                this.$set(this.ruleForm, 'scheduleGroupId', null);
                this.$set(this.ruleForm, 'scheduleShiftId', null);
                this.$set(this.ruleForm, 'scheduleShiftName', null);
                this.$set(this.ruleForm, 'scheduleShiftCode', null);
                this.$set(this.ruleForm, 'prdReportMachineList', []);
                this.scheduleShiftList = [];
                this.$set(this.ruleForm, 'empList', []);
                this.$set(this.ruleForm, 'productList', []);
                this.$set(this.ruleForm, 'matchProductList', []);
                this.getDateScheduleShiftOptionRequest();
            },
            getDateScheduleShiftOptionRequest() {
                if (this.ruleForm.workshopId && this.ruleForm.belongDate) {
                    return workforcemanagementScheduleList({
                        belongDate: [this.ruleForm.belongDate, this.ruleForm.belongDate],
                        workshopId: this.ruleForm.workshopId
                    }).then(res => {
                        if (res.data.status === 200) {
                            const resData = res.data.res;
                            if (resData && resData.length) {
                                this.scheduleShiftList = resData[0].scheduleShiftList;
                            } else {
                                tipsBar(this, 'custom', 'warning', '当前时间未排班，请排班后再操作！');
                            }
                        }
                    });
                }
            },
            onSelectBatchChange(e, rowIndex, cellIndex) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm.subTitleList[rowIndex].productUseCommunicationItemList[cellIndex], 'batchId', e.id);
                    this.$set(this.ruleForm.subTitleList[rowIndex].productUseCommunicationItemList[cellIndex], 'batchCode', e.batchCode);
                }
            },
            onSelectProductChange(e, rowIndex, cellIndex) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm.subTitleList[rowIndex].productUseCommunicationItemList[cellIndex], 'productId', e.id);
                    this.$set(this.ruleForm.subTitleList[rowIndex].productUseCommunicationItemList[cellIndex], 'productCode', e.code);
                    this.$set(this.ruleForm.subTitleList[rowIndex].productUseCommunicationItemList[cellIndex], 'productName', e.name);
                    this.$set(this.ruleForm.subTitleList[rowIndex].productUseCommunicationItemList[cellIndex], 'productModels', e.models);
                }
            },
            onSelectEmpChange(e) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm, 'empId', e.id);
                    this.$set(this.ruleForm, 'empName', e.name);
                }
            },
            onAddMachineBtn({ rowIndex }) {
                this.ruleForm.subTitleList[rowIndex].productUseCommunicationItemList.push({
                    'batchCode': '',
                    'batchId': 0,
                    'color': '',
                    'dosage': '',
                    'extendText': '',
                    'productCode': '',
                    'productId': 0,
                    'productModels': '',
                    'productName': '',
                    'remark': '',
                    'subTitle': ''
                });
            },
            onAddBtn() {
                this.ruleForm.subTitleList.push({
                    subTitle: null,
                    productUseCommunicationItemList: []
                });
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                const item = this.workshopList.find(x => x.id === params.workshopId) || {};
                params.workshopCode = item.code;
                params.workshopName = item.name;

                const areaItem = this.workshopAreaList.find(x => x.id === params.workshopAreaId) || {};
                params.workshopAreaCode = areaItem.code;
                params.workshopAreaName = areaItem.name;
                return params;
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                // 新增
                if (!this.dataId) {
                    this.ruleForm.id = null;
                    spinReportProductOpenRecordCreate(this.getParamData()).then(res => {
                        this.saveBtnLoading = false;
                        if (res.data.status === 200) {
                            this.$tipsBar(this, 'save');
                            // 生产订单-远程搜索组件用到，需返回ID
                            this.$emit('on-finish', res.data.res);
                        }
                    });
                    return;
                }

                // 编辑
                spinReportProductOpenRecordUpdate(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return spinReportProductOpenRecordGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res;
                    }
                });
            },
            getWorkshopAreaListRequest() {
                return spinWorkshopAreaPage({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.workshopAreaList = res.data.res;
                    }
                });
            },
            getPostListRequest() {
                return systemPostPage({
                    auditState: 1
                }).then(res => {
                    if (res.data.status === 200) {
                        this.allPost = res.data.res ? res.data.res.map(x => {
                            return {
                                totalQty: 0,
                                leaveQty: 0,
                                processCode: x.processCode,
                                sortNum: x.sortNum,
                                postId: x.id,
                                postName: x.name
                            };
                        }) : [];
                        this.postList = this.allPost.filter(x => ['XS', 'LT'].includes(x.processCode)).sort((a, b) => {
                            return a.sortNum - b.sortNum;
                        });
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                if (!this.dataId) {
                    this.$set(this.ruleForm, 'belongDate', formatDate(Date.now()));
                    this.$set(this.ruleForm, 'empId', this.$store.state.user.empInfo.id);
                    this.$set(this.ruleForm, 'empName', this.$store.state.user.empInfo.name);
                    this.$set(this.ruleForm, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                }
                await this.getPostListRequest();
                if (this.dataId) await this.getDetailRequest();
                await this.getWorkshopAreaListRequest();
                await this.getDateScheduleShiftOptionRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
<style scoped lang="scss">
    .option-item-title {
        height: 38px;
        font-size: 14px;
        display: flex;
        justify-content: center;
        align-items: center;
        background: #e8eaec;
        border-radius: 4px 4px 0 0;
    }
</style>
